package com.flying.rp.chapter2.comp;

import com.flying.rp.chapter2.model.Temperature;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import rx.Observable;

import java.util.Random;
import java.util.concurrent.TimeUnit;


@Component
public class TemperatureSensor {
    private final Random rnd;
    private final Observable<Temperature> dataStream;


    public TemperatureSensor(ApplicationEventPublisher publisher) {
        this.rnd = new Random();
        this.dataStream = Observable.range(0, Integer.MAX_VALUE)
                .concatMap(tick -> Observable.just(tick)
                        .delay(rnd.nextInt(5), TimeUnit.SECONDS)
                        .map(tickValue -> this.probe()))
                .publish()
                .refCount();
    }

    private Temperature probe() {
        return new Temperature(16 + rnd.nextGaussian() * 10);
    }

    public Observable<Temperature> temperatureStream() {
        return dataStream;
    }
}
